package com.mf.controller.admin;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.mf.entity.*;
import com.mf.entity.vo.GoodsVO;
import com.mf.service.*;
import com.mf.util.OrderSNUtil;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 订单
 *
 * @author: Jiang Runqing
 * @date: 2018-09-10 21:04
 */
@RestController
@RequestMapping("/admin/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderGoodsService orderGoodsService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private LogService logService;

    @Autowired
    private CustomerService customerService;

    @RequestMapping("/list")
    @RequiresPermissions(value = {"订单管理"}, logical = Logical.OR)
    public Map<String, Object> list(Order order,
                                    @RequestParam(value = "page", required = false) Integer page,
                                    @RequestParam(value = "rows", required = false) Integer rows) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        User currentUser = (User) request.getSession().getAttribute("currentUser");
        List<Order> orderList = null;
        List<Order> orderList1 = new ArrayList<>();
        Boolean flag = true;
        if (null == currentUser) {
            resultMap.put("success", false);
            resultMap.put("errorInfo", "用户过期，请重新登录！");
            return resultMap;
        }
        if (currentUser.getRemarks().contains("管理") || currentUser.getRemarks().contains("经理")) {
            orderList = orderService.list(order, page, rows, Sort.Direction.ASC, "id");
        } else {
            flag = false;
            order.setUserId(currentUser.getId());
            orderList = orderService.list(order, page, rows, Sort.Direction.ASC, "id");
        }

        for (Order or : orderList) {
            Customer c = customerService.findById(or.getCustomerId());
            or.setCustomerName(c.getName());
            orderList1.add(or);
        }


        Long total = orderService.getCount(order);
        resultMap.put("rows", orderList1);
        resultMap.put("total", total);
        resultMap.put("isLeader", flag);
        logService.save(new Log(Log.SEARCH_ACTION, "查询订单列表信息"));
        return resultMap;
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @RequiresPermissions(value = "订单管理")
    public Map<String, Object> save(@RequestParam(value = "goodsJson", required = false) String goodsJson, Order order) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        User currentUser = (User) request.getSession().getAttribute("currentUser");
        if (null == currentUser) {
            resultMap.put("success", false);
            resultMap.put("errorInfo", "用户过期，请重新登录！");
            return resultMap;
        }
        Gson gson = new Gson();
        JsonParser parser = new JsonParser();
        JsonArray jarray = parser.parse(goodsJson).getAsJsonArray();


        if (order.getOrderId() != null) {
            logService.save(new Log(Log.UPDATE_ACTION, "更新订单信息" + order));
        } else {
            logService.save(new Log(Log.ADD_ACTION, "添加订单信息" + order));
        }
        order.setOrderSN(new OrderSNUtil().createOrderSN());//生成订单编号
        if (null == order.getOrderStatus()) {
            order.setOrderStatus(0);   //订单状态  0待确定  1已完成  2已作废
        }
        order.setUserId(currentUser.getId());
        order.setAddTime(new Date());
//        order.setOrderAmount();
        orderService.save(order);

        if (jarray.size() > 0) {
            for (JsonElement obj : jarray) {
                GoodsVO goodsVO = gson.fromJson(obj, GoodsVO.class);
                System.out.println(goodsVO);
                OrderGoods orderGoods = new OrderGoods();

                orderGoods.setGoodsId(goodsVO.getGoodsId());
                if (null != order.getOrderId()) {
                    orderGoods.setOrderId(order.getOrderId());
                }
                orderGoods.setGoodsNum(goodsVO.getGoodsNum());
                orderGoods.setUnit(goodsVO.getUnit());
//                orderGoods.setGoodsSN(order.getOrderSN());
                orderGoodsService.save(orderGoods);
            }
        }
        resultMap.put("success", true);
        return resultMap;
    }

    @GetMapping("/getOne")
    @RequiresPermissions(value = "订单管理")
    public Order getById(int orderId) {
        Order order = orderService.getById(orderId);
        if (null == order) {
            return null;
        }

        Customer customer = customerService.findById(order.getCustomerId());
        order.setCustomer(customer);

        List<OrderGoods> orderGoodsList = orderGoodsService.getListByOrderId(order.getOrderId());
        List<Goods> goodsList = new ArrayList<>();
        List<GoodsVO> goodsVOList = new ArrayList<>();

        for (OrderGoods og : orderGoodsList) {

            goodsList.add(goodsService.findById(og.getGoodsId()));
        }

        order.setOrderGoodsList(orderGoodsList);

        order.setGoodsList(goodsList);

        System.out.println(order);

        return order;
    }

    /**
     * 流程审批
     *
     * @param order
     * @return
     */
    @RequestMapping(value = "/approve", method = RequestMethod.POST)
    public Map<String, Object> approve(Order order) {
        Map<String, Object> resultMap = new HashMap<>();

        if (null == order) {
            resultMap.put("success", false);
            resultMap.put("errorInfo", "订单Id错误");
            return resultMap;
        }

        if (order.getOrderId() != null && order.getOrderStatus() == 1) {

            logService.save(new Log(Log.UPDATE_ACTION, "订单审核通过" + order));
        } else {
            logService.save(new Log(Log.ADD_ACTION, "订单被驳回" + order));
        }

        orderService.updateStatus(order);
        resultMap.put("success", true);
        return resultMap;
    }

}
